package com.study.ws.config.ws.annotation;

import com.study.ws.config.ws.session_manager.ISessionManager;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import jakarta.websocket.server.ServerEndpointConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author xl-9527
 * @since 2025/3/27
 **/
@Component
@ServerEndpoint(value = "/annotation-ws/{userId}", configurator = TextMessageAnnotationHandler.CustomConfig.class)
public class TextMessageAnnotationHandler {

    private final Logger log = LoggerFactory.getLogger(TextMessageAnnotationHandler.class);

    private final ISessionManager<Session> iSessionManager;
    public static TextMessageAnnotationHandler SELF;

    public TextMessageAnnotationHandler(final ISessionManager<Session> iSessionManager) {
        this.iSessionManager = iSessionManager;
        SELF = this;
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") final Integer userId) {
        log.info("userId -> {}", userId);
        iSessionManager.addSession(session, userId);
    }

    @OnMessage
    public void onMessage(Session session, final String message, @PathParam("userId") final Integer userId) {
        log.info("userId -> {}, message -> {}", userId, message);
        for (final Session optherSession : iSessionManager.getAllSession()) {
            if (session != optherSession) {
                optherSession.getAsyncRemote().sendText("server: i receive message -> [" + message + "]");
            }
        }
    }


    public static class CustomConfig extends ServerEndpointConfig.Configurator {

        @Override
        @SuppressWarnings("unchecked")
        public <T> T getEndpointInstance(final Class<T> clazz) {
            return (T) TextMessageAnnotationHandler.SELF;
        }
    }
}
